import React, { useEffect, useState, useRef } from 'react'
import { Form, Input, Switch, Button, Upload, TreeSelect, message, Image } from 'antd'
import { updateCate, getCateDetail } from '@a/cate'
import { useNavigate } from 'react-router-dom'

export default function CateAdd(props: any) {
  const navigate = useNavigate()
  const formRef = useRef(null);
  // 处理当前表单修改分类初始值
  const fetchCateDetail = () => {
    getCateDetail({
      id: props.cateId
    }).then(res=> {
      if (res.data.code === 200) {
        formRef.current.setFieldsValue(res.data.data)
        // 设置分类图标的初始值
        setIcon(res.data.data.cateIcon)
      }
      
    })
  }
  useEffect(() => {
    fetchCateDetail()
  }, [props.cateId])

  // 提交表单
  const submitCate = (params = {}) => {
  //  发送请求 给出提示即可
  updateCate({
      ...params,
      cateIcon
    }).then(res => {
      if (res.data.code === 200) {
        message.success(res.data.msg, 2, () => {
          // 刷新
          navigate(0)
        })
      }
      
    })
  }
  // 上传 图片回调
  const [cateIcon, setIcon] = useState('')
  
  const uploadStateChange = (info: any) => {
    if(info.file.status === 'done') {
      // 上传完成
      if (info.file.response.code === 200) {
        setIcon(info.file.response.data.url)
      }
    }
  }
  return (
    <Form
      name="basic"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600 }}
      onFinish={submitCate}
      ref={formRef}
    >
      <Form.Item
        label="商品分类名"
        name="cateName"
        rules={[
          { required: true, message: '分类名必填!' }
        ]}
      >

        <Input />
      </Form.Item>
      <Form.Item
        label="是否启用"
        name="enable"
        valuePropName="checked"
        rules={[
          { required: true, message: '必须选择启用!' }
        ]}
      >
        <Switch />
      </Form.Item> 
      <Form.Item
        label="父级分类"
        name="pid"
        rules={[
          { required: true, message: '父级分类必填!' }
        ]}
      >
        <TreeSelect
          showSearch
          style={{ width: '100%' }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          placeholder="选择父级分类"
          allowClear
          treeDefaultExpandAll
          treeData={props.cates}
          fieldNames={{
            label: 'cateName',
            value: 'id',
            children: 'children'
          }}
        />
      </Form.Item>
      <Form.Item label="分类图标">
          <Upload
            name='file'
            action="/api/upload"
            accept='.jpg, .png, .gif'
            onChange = {
              uploadStateChange
            }
          >
            <Button>点击上传</Button>
          </Upload>
          <Image src={cateIcon}/>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" htmlType="submit">
          确定
        </Button>
      </Form.Item>
    </Form>
  )
}
